from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from utils.permission_required import permission_required
import WSGI
import json as simplejson
import logging
import math
import webapp2

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiHangSanXuatHomNay(webapp2.RequestHandler):
    priv = ''
    perm = 'Xuong.HangSanXuatHomNay'
    @permission_required
    def get(self):
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/HangSanXuatHomNay.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'Xuong.HangSanXuatHomNay'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListHangSanXuat': 'getListHangSanXuat'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListHangSanXuat(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        rows, rowNum = DaoQuanLyNhanVien.getListHangSanXuatHomNay((dt.now() + datetime.timedelta(hours=7)).date(), gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
   
        
        
            
        